import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Animated,
    Platform,
    TouchableNativeFeedback,
    InteractionManager,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import StorageUser from '../lib/plugins/StorageUser';
import NavigationBar from '../components/NavigationBar';
import shopService from '../lib/services/shopService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');
export default class DrawCash extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.state = {
            totalMoney:this.props.navigation.state.params.userMoney,
            remindText:'',
            canSubmit:false,
            moneyText:'',
            bankName:'',
            cardList:[],
            cardNum:'',
            index:0,
        };
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getCardList();
                });            
            }).catch(err=> {
                console.log(err)
            });
    }
    
    render(){
        var num = '';
        if(this.state.cardNum){
            num = '（'+this.state.cardNum.slice(-4)+'）';
        }
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'提现'} 
                    leftPress={()=>this.goBack()}
                    rightText={'记录'}
                    rightTextPress={()=>this.goDrawRecord()}
                    rightTextStyle={{color:'#fff',fontSize:16}}/>
                <ScrollView>
                    <View style={styles.box}>
                        <View>
                            <Text style={{color:'#333',fontSize:16}}>可提现金额：￥{this.state.totalMoney}</Text>
                        </View>
                        <View style={styles.choseCard}>
                            <Text style={{marginRight:20,color:'#333'}}>到账银行卡</Text>
                            <Text onPress={()=>this.goBankCardList()} style={{color:'rgb(79,145,237)'}}>{this.state.bankName+num}</Text>
                        </View>
                        <Text style={{marginTop:5,color:'#333',marginBottom:5}}>提现金额</Text>
                        <View style={[styles.choseCard,{borderBottomWidth:1,borderBottomColor:'#ccc',paddingBottom:5}]}>
                            <Text style={{fontSize:20,color:'#333'}}>￥</Text>
                            <TextInput 
                                style={{flex:1,padding:3,fontSize:24,marginLeft:10}}
                                maxLength={10}
                                onChangeText={(text)=>this.getMoneyText(text)}
                                defaultValue={this.state.moneyText}
                                keyboardType={'numeric'}
                                underlineColorAndroid="transparent" 
                                selectionColor={'#aaa'}/>
                        </View>
                        <View style={{height:50}}>
                            <Text>{this.state.remindText}</Text>
                        </View>
                    </View>
                    <View style={styles.submitBtn}>
                        <TouchableOpacity onPress={()=>this.submitData()}>
                            <View style={{backgroundColor:'rgb(79,145,237)',height:40,alignItems:'center',justifyContent:'center',borderRadius:3,width:width*2/3}}>
                                <Text style={{color:'#fff',fontSize:16}}>提 现</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </ScrollView>
                
            </View>
        )
    }
    // 返回按钮
    goBack(){
        this.props.navigation.state.params.upData(this.state.totalMoney)
        this.props.navigation.goBack();
    }
    goDrawRecord(){
        const {navigate } = this.props.navigation;
        navigate('DrawRecord')
    }
    goBankCardList(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('BankCardList',{cardList:$this.state.cardList,num:$this.state.index,upData:(data,index)=>{
            $this.setState({
                bankName:data.card_type.split('-')[0],
                cardId:data.card_id,
                cardNum:data.card_num,
                index:index
            })
        }})
    }
    // 获取输入的提现金额
    getMoneyText(text){
        var staturs = false;
        var remindText = '';
        var num = text.replace(/^\s$/g,'');
        
        if((this.state.totalMoney-0)>=(num-0)){
            staturs = true;
        }else{
            staturs = false;
            remindText = '输入金额大于可提现金额';
        }
        if(num==''){
            staturs = false;
            remindText = '';
        }else if(/^\d+[.]?\d{0,2}$/.test(num) && (num!=0 || num!=0.0 || num!=0.00)){
            this.setState({
                moneyText:num,
                canSubmit:staturs,
                remindText:remindText
            })
        }else{
            remindText = '请输入正确的金额'
            this.setState({
                moneyText:num,
                canSubmit:false,
                remindText:remindText
            })
        }
    }
    // 点击提现按钮
    submitData(){
        var $this = this;
        if(this.state.canSubmit){
            // alert('ok');

            var str = this.state.bankName+'('+this.state.cardNum+')';
            console.log(str)
            shopService.subBankMoneyApply(function(data){
                // alert(JSON.stringify(data))
                // console.log(data)
                if(data.code==10000){
                    Alert.alert(
                        '提示信息',
                        '申请已发送！',
                        [{text: '确定', onPress: () => {
                                $this.setState({
                                    totalMoney:($this.state.totalMoney-$this.state.moneyText)
                                })
                                $this.goBack()
                            }
                        }])
                }else{
                    alert('申请失败！')
                }
            },$this.userId,str,$this.state.moneyText,$this.token)
        }else{
            Alert.alert(
                '提示信息',
                '所填金额有错误！',
                [{text: '确定'}]
            )
        }
    }
    // 获取银行卡列表
    getCardList(){
        var $this = this;
        shopService.userBindBankLists(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.setState({
                    cardList:data.data,
                    bankName:data.data[0].card_type.split('-')[0],
                    cardId:data.data[0].card_id,
                    cardNum:data.data[0].card_num,
                })
            }
        },$this.userId,$this.token)
    }


}
const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),
    },
    box:{
        marginTop:10,
        marginLeft:10,
        marginRight:10,
        backgroundColor:'#fff',
        padding:10,
        paddingLeft:30,
        paddingRight:30
    },
    choseCard:{
        flexDirection:'row',
        marginTop:5,
        paddingRight:60
    },





    submitBtn:{
        marginTop:80,
        alignItems:'center'
    },

});